package com.fsd.admin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.E_WechatService;
import com.fsd.admin.service.impl.E_wechatCoreService;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.wechat.entity.WeChat;
import com.fsd.core.wechat.util.SignUtil;

@Controller
@RequestMapping("/e_wechat")
public class E_WechatApiController extends AdminController {
	
	private static final Logger log = Logger.getLogger(E_WechatApiController.class);
	
    @Resource(name = "e_wechatServiceImpl")
	private E_WechatService objectService;
	
	/**
	 * 验证开发者模式
	 * @param wc
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/apitest.do",method = RequestMethod.GET)
	@ResponseBody
	public String inittest(WeChat wc, HttpServletRequest request, HttpServletResponse response){
		// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String signature = wc.getSignature(); //微信加密签名
		String timestamp = wc.getTimestamp(); // 时间戳
	    String nonce = wc.getNonce(); //随机数
	    String echostr = wc.getEchostr(); //随机字符串
	    System.out.println(signature);
	    // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignatureTest(signature, timestamp, nonce)) {
        	return echostr;
        } else {
        	System.out.println("不是微信服务器发来的请求,请小心!");  
            return null;
        }
	}
	
	/**
	 * 验证开发者模式
	 * @param wc
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/api.do",method = RequestMethod.GET)
	@ResponseBody
	public String init(WeChat wc, HttpServletRequest request, HttpServletResponse response){
		System.out.println("进来了");
		Object apiid = request.getParameter("apiid");
		if (apiid == null || apiid.equals("")){
			log.error("微信服务器发来的请求,未获取到访问参数APIID信息!");
        	System.out.println("微信服务器发来的请求,未获取到访问参数APIID信息!");
        	return null;
		}
		E_wechat objWC = null;
		try {
			objWC = objectService.getObjectByApiId(apiid.toString());
		} catch (Exception e) {
			log.error("微信服务器发来的请求,根据访问参数APIID获取信息失败! error:{0}", e);
			System.out.println("微信服务器发来的请求,根据访问参数APIID获取信息失败!");
		}
		if(objWC == null)
			return null;
		if (objWC.getToken() == null || objWC.getToken().equals("")){
			log.error("微信服务器发来的请求,微信账号数据库未保存令牌信息!");
        	System.out.println("微信服务器发来的请求,微信账号数据库未保存令牌信息!");
			return null;
		}
		// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String signature = wc.getSignature(); //微信加密签名
		String timestamp = wc.getTimestamp(); // 时间戳
	    String nonce = wc.getNonce(); //随机数
	    String echostr = wc.getEchostr(); //随机字符串
	    // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(objWC.getToken(), signature, timestamp, nonce)) {
        	return echostr;
        } else {
			log.error("不是微信服务器发来的请求,请小心!");
            return null;
        }
	}
	
	/**
	 * 接收、处理、响应消息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/api.do", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getWechatMessage(HttpServletRequest request, HttpServletResponse response) throws Exception{
		E_wechatCoreService coreSerive = new E_wechatCoreService();
		Object apiid = request.getParameter("apiid");
		if (apiid == null || apiid.equals("")){
			log.error("微信服务器发来的请求,未获取到访问参数APIID信息!");
        	System.out.println("微信服务器发来的请求,未获取到访问参数APIID信息!");
        	return coreSerive.processRequest(request, "访问服务器接口，未传入指定访问参数APIID信息!");
		}
		E_wechat objWC = null;
		try {
			objWC = objectService.getObjectByApiId(apiid.toString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("微信服务器发来的请求,根据访问参数APIID获取信息失败! error:{}", e);
			System.out.println("微信服务器发来的请求,根据访问参数APIID获取信息失败!");
			return coreSerive.processRequest(request, "访问服务器接口，根据访问参数APIID获取信息失败!" + e.getMessage());
		}
		if(objWC == null || objWC.getId() == null){
			return coreSerive.processRequest(request, "访问服务器接口，获取APIID信息为空!");
		}
        // 初始化配置文件
		//调用CoreService类的processRequest方法接收、处理消息，并得到处理结果
        String respMessage = coreSerive.processRequest(objWC, request);
        // 响应消息
        return respMessage;
	}

    /**
     * 测试自动回复接口
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/test_Message.do")
    public @ResponseBody Object testMessage(ParametersUtil parameters) throws Exception{
    	return ParametersUtil.sendList(objectService.testMessage(parameters));
    }
}
